//
//  EAGLView.m
//  XIEngine
//
//  Created by Bazsi on 22.05.09.
//  Copyright Universität Basel 2009. All rights reserved.
//


#import <QuartzCore/QuartzCore.h>
#import "XIEngine.h"
#import "EAGLView.h"
//#import <OpenGLES/EAGLDrawable.h>

#define USE_DEPTH_BUFFER 0

// A class extension to declare private methods
@interface EAGLView ()


@property (nonatomic, retain) EAGLContext *context;
//@property (nonatomic, assign) NSTimer *animationTimer;

- (BOOL) createFramebuffer;
- (void) destroyFramebuffer;

@end


@implementation EAGLView

@synthesize context;
//@synthesize fpsLabel;
//@synthesize animationTimer;
//@synthesize animationInterval;


// You must implement this method
+ (Class)layerClass {
    return [CAEAGLLayer class];
}



//The GL view is stored in the nib file. When it's unarchived it's sent -initWithCoder:
- (id)initWithCoder:(NSCoder*)coder {
    
    if ((self = [super initWithCoder:coder])) {
        // Get the layer
        CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
        
        eaglLayer.opaque = YES;
        eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                        [NSNumber numberWithBool:NO], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
        
        context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
        
        if (!context || ![EAGLContext setCurrentContext:context]) {
            [self release];
            return nil;
        }
        
     //   animationInterval = 1.0 / 60.0;
		
		// Set up coordinate system.
		CGRect rect = [[UIScreen mainScreen] bounds];
		//NSLog(@"w:%f, h:%f", rect.size.width, rect.size.height);
		glOrthof(0, rect.size.height, rect.size.width, 0, -1, 1);
		//glRotatef(-90, 0, 0, 1);
		//glTranslatef(-480, 0, 0);
		
		
		//fpsSample = [[NSMutableArray alloc] initWithCapacity:100];
		//fpsLastUpdate = [[NSDate date] retain];
		// Initialize game world.
		//_game = [[MyGame alloc] init];

    }
    return self;
}


/*- (void)drawView {
    
    [EAGLContext setCurrentContext:context];
    
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
    glViewport(0, 0, backingWidth, backingHeight);
    
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
	
    glMatrixMode(GL_MODELVIEW);
    
    glClearColor(0.35f, 0.7f, 0.92f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	
	// Draw the current state of the game.
	[[XIGame sharedGame] draw];

	glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
    [context presentRenderbuffer:GL_RENDERBUFFER_OES];
}*/

- (void)prepareForNewFrame
{
	[EAGLContext setCurrentContext:context];
    
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
    glViewport(0, 0, backingWidth, backingHeight);
    
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
	
    glMatrixMode(GL_MODELVIEW);
    
    //glClearColor(0.35f, 0.7f, 0.92f, 1.0f);
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	//glEnableClientState(GL_COLOR_ARRAY);
}

- (void)finalizeFrame
{
	glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
    [context presentRenderbuffer:GL_RENDERBUFFER_OES];
}

/*- (void)updateFPS
{
	// If needed draw the current fps.
#ifdef kXIShowFPS
	NSTimeInterval interval = -[[XIGame sharedGame].lastUpdate timeIntervalSinceNow];
	int currentFPS = (int)round(1.0/interval);
	[fpsSample addObject:[NSNumber numberWithInt:currentFPS]];
	if([fpsSample count] > 20){[fpsSample removeObjectAtIndex:0];}
	if(-[fpsLastUpdate timeIntervalSinceNow] > kXIFPSUpdateInterval)
	{
		float average = 0;
		for(NSNumber *number in fpsSample){average += [number intValue];}
		average /= [fpsSample count];
		fpsLabel.text = [NSString stringWithFormat:@"%i", (int)round(average)];
		if(fpsLastUpdate){[fpsLastUpdate release];}
		fpsLastUpdate = [[NSDate date] retain];
	}
#endif
}*/


- (void)layoutSubviews {
    [EAGLContext setCurrentContext:context];
    [self destroyFramebuffer];
    [self createFramebuffer];
    //[self drawView];
	
#ifdef kXIShowFPS
	//fpsLabel.hidden = NO;
#else
	//fpsLabel.hidden = YES;
#endif
	
}


- (BOOL)createFramebuffer {
    
    glGenFramebuffersOES(1, &viewFramebuffer);
    glGenRenderbuffersOES(1, &viewRenderbuffer);
    
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
    [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);
    
    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
    
    if (USE_DEPTH_BUFFER) {
        glGenRenderbuffersOES(1, &depthRenderbuffer);
        glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
        glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
        glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
    }
    
    if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
        NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
        return NO;
    }
    
    return YES;
}


- (void)destroyFramebuffer {
    
    glDeleteFramebuffersOES(1, &viewFramebuffer);
    viewFramebuffer = 0;
    glDeleteRenderbuffersOES(1, &viewRenderbuffer);
    viewRenderbuffer = 0;
    
    if(depthRenderbuffer) {
        glDeleteRenderbuffersOES(1, &depthRenderbuffer);
        depthRenderbuffer = 0;
    }
}




- (void)dealloc {
    
    
    if ([EAGLContext currentContext] == context) {
        [EAGLContext setCurrentContext:nil];
    }
    
	//[fpsSample release];
	//[fpsLabel release];
	//[fpsLastUpdate release];
    [context release];  
    [super dealloc];
}

#pragma mark -
#pragma mark Touch handling

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
	
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	
}

@end
